package cgs

import (
	"cgs-server/helper"
	"cgs-server/server"
	"fmt"
	"net/http"
	"os"
	"strings"
)

func init() {
	//server.Handle(http.MethodPost, "/api/Cgs/SaveSnap", SaveSnap,server.None)
	server.Post("/api/Cgs/SaveSnap", SaveSnap, "保存工程配置信息", server.None)
}

func SaveSnap(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	projId := strings.TrimSpace(r.FormValue("projectID"))
	data := strings.TrimSpace(r.FormValue("data"))
	fileName := "config.json"
	savePath := fmt.Sprintf("/Upload/Cgs/%v", projId)
	//filePath := fmt.Sprintf("%v/%v", savePath, fileName)
	physicalPath := server.MapPath(savePath)

	if _, err := os.Stat(physicalPath); os.IsNotExist(err) {
		os.MkdirAll(physicalPath, 0755)
	}
	target, err := os.Create(fmt.Sprintf("%v/%v", physicalPath, fileName))
	defer target.Close()
	if err != nil {
		helper.WriteJSON(w, server.Fail(err.Error()))
		return
	} else {
		data = helper.MinifyJson(data)
		_, err = target.WriteString(data)
		if err != nil {
			helper.WriteJSON(w, server.Fail(err.Error()))
			return
		}
	}
	helper.WriteJSON(w, server.Result{
		Code: 200,
		Msg:  "Saved successfully!",
	})
}
